<template>
  <div class="app-container">
    <el-row :gutter="10" style="margin-bottom:20px;">
      <el-col :span="5.5">
        <el-select
          v-model="searchValue.activity_id"
          placeholder="请选择活动主题"
          clearable
          filterable
          class="titlebus"
          @change="changeWork"
        >
          <el-option
            v-for="item in themeList"
            :label="item.title"
            :value="item.activity_id"
            :key="item.activity_id"
          ></el-option>
        </el-select>
      </el-col>
      <el-col :span="3">
        <el-input v-model="searchValue.username" placeholder="作者ID" clearable></el-input>
      </el-col>
      <el-col :span="3">
        <el-input v-model="searchValue.work_name" placeholder="作品名称" clearable></el-input>
      </el-col>

      <el-col :span="1.5">
        <el-button style=" background: #00BFD6; color: #FFFFFF; " @click="fetchData">
          搜索
          <i class="el-icon-search"></i>
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          @click="loadExcel"
          :loading="downloadLoading"
          style=" background: #ff9e6d; color: #FFFFFF; "
        >导出筛选作品</el-button>
      </el-col>
      <el-col :span="3">
        <el-select
          v-model="searchValue.level"
          placeholder="审核状态"
          clearable
          filterable
          @change="fetchData"
        >
          <el-option
            v-for="item in stateList"
            :label="item.label"
            :value="item.val"
            :key="item.val"
          ></el-option>
        </el-select>
      </el-col>
      <el-col :span="4">
        <!-- <el-button style=" background: #00BFD6; color: #FFFFFF; " @click="fetchData">
          排序
          <i class="el-icon-sort"></i><i class="el-icon-sort-up"></i><i class="el-icon-sort-down"></i>
        </el-button>-->
        <el-button :style="{ background: '#00BFD6', color: '#FFFFFF' }" @click="toggleSortOrder">
          排序
          <i  class="el-icon-sort"></i>
        </el-button>
      </el-col>
    </el-row>
    <el-table
      :data="tableData"
      border
      v-loading="listLoading"
      element-loading-text="Loading"
      highlight-current-row
      style="width:100%;"
    >
      <el-table-column type="index" label="序号" width="60"></el-table-column>
      <el-table-column prop="cover" label="缩略图" width="160">
        <template slot-scope="scope">
          <img
            :src="scope.row.cover"
            alt
            style="width:120px;height:80px;object-fit: cover; margin:10px 0"
          />
        </template>
      </el-table-column>
      <el-table-column prop="work_name" label="作品名称" min-width="150"></el-table-column>
      <el-table-column prop="username" label="作者ID" min-width="150"></el-table-column>
      <el-table-column prop="work_link" label="作品链接" min-width="180"></el-table-column>
      <el-table-column prop="level1" width="180">
        <template slot="header">
          <div style="display:flex ; algin-item:center;">
            <span style="color:#45cbdd; cursor: pointer;" @click="toDetailAll(0)">一审(总明细)</span>
            <span>
              <img
                src="../../../assets/detail-icon.jpg"
                alt
                style="width:14px ; margin-left:5px;vertical-align: middle;"
              />
            </span>
          </div>
        </template>
        <template slot-scope="scope">
          一围总票{{scope.row.level1 || 0}}票
          <el-button
            style="background-color:#e5f8fc; color:#2dcadf; border:1px solid #00BFD6;margin-left:5px;"
            size="mini"
            @click="toDetail(scope.row,0)"
          >明细</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="level2" width="180">
        <template slot="header">
          <div style="display:flex ; algin-item:center; ">
            <span style="color:#45cbdd; cursor: pointer;" @click="toDetailAll(1)">二审(总明细)</span>
            <span>
              <img
                src="../../../assets/detail-icon.jpg"
                alt
                style="width:14px ; margin-left:5px;vertical-align: middle;"
              />
            </span>
          </div>
        </template>
        <template slot-scope="scope">
          总星数{{scope.row.level2 || 0}}
          <el-button
            style="background-color:#e5f8fc; color:#2dcadf; border:1px solid #00BFD6;margin-left:5px;"
            size="mini"
            @click="toDetail(scope.row, 1)"
          >明细</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="level3" width="180">
        <template slot="header">
          <div style="display:flex ; algin-item:center;">
            <span style="color:#45cbdd; cursor: pointer;" @click="toDetailAll(2)">三审(总明细)</span>
            <span>
              <img
                src="../../../assets/detail-icon.jpg"
                alt
                style="width:14px ; margin-left:5px;vertical-align: middle;"
              />
            </span>
          </div>
        </template>
        <template slot-scope="scope">
          平均分{{scope.row.level3 || 0}}
          <el-button
            style="background-color:#e5f8fc; color:#2dcadf; border: 1px solid #00BFD6;margin-left:5px;"
            size="mini"
            @click="toDetail(scope.row, 2)"
          >明细</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin:40px 0">
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="searchValue.page"
        :limit.sync="searchValue.limit"
        @pagination="fetchData"
      />
    </div>
  </div>
</template>

<script>
import axios from "axios";
import { getWorksList, getWorksExportAll } from "@/api/works";
import { getActivityList } from "@/api/activity";
export default {
  data() {
    return {
      searchValue: {
        activity_id: null, //活动id
        work_name: null,
        username: null,
        sort_order: 'desc',
        level: null,
        page: 1,
        limit: 10
      },
      total: 0,
      title: null,
      downloadLoading: false,
      listLoading: false,
      tableData: [],
      themeList: [], //活动名称列表
      stateList: [
        {
          label: "评审一",
          val: 1
        },
        {
          label: "评审二",
          val: 2
        },
        {
          label: "评审三",
          val: 3
        }
      ], //状态列表
      downloadUrl: null,
      filename: ""
    };
  },
  created() {
    getActivityList().then(res => {
      this.themeList = res.list;
      const firstOption = this.themeList[0];
      if (firstOption) {
        this.searchValue.activity_id = firstOption.activity_id;
        this.title = firstOption.title;
        this.filename = `${firstOption.title}.xlsx`;
        this.fetchData();
      }
    });
  },
  methods: {
    toggleSortOrder() {
      if (this.searchValue.sort_order === 'asc') {
        this.searchValue.sort_order = "desc"; // 如果没有排序，则设置为升序
      } else if (this.searchValue.sort_order === "desc") {
        this.searchValue.sort_order = "asc"; // 如果是升序，则切换到降序
      } 
      this.fetchData(); // 根据新的排序状态获取数据
    },
    changeWork(value) {
      let themtype = this.themeList.find(item => item.activity_id === value);
      this.title = themtype.title;
    },
    toDetailAll(level) {
      this.$router.push({
        path: "/statistics/work/all-detail/",
        query: {
          activity_id: this.searchValue.activity_id,
          level: level,
          title: this.title
        }
      });
    },
    toDetail(item, level) {
      this.$router.push({
        path: "/statistics/work/detail/",
        query: {
          activity_id: item.activity_id,
          title: item.title,
          work_id: item.work_id,
          level: level,
          title: this.title
        }
      });
    },
    handleSizeChange(val) {
      this.searchValue.limit = val;
      this.fetchData();
    },

    async loadExcel() {
      try {
        this.downloadLoading = true;
        this.$message("正在导出，请稍等...");

        const params = {
          activity_id: this.searchValue.activity_id
        };

        const url = `${
          process.env.VUE_APP_BASE_API
        }/api/works/export?activity_id=${encodeURIComponent(
          params.activity_id
        )}`;

        const response = await axios.get(url, {
          headers: {
            "X-token": this.$store.getters.token || ""
          },
          responseType: "blob" // 设置响应类型为 Blob
        });

        await this.triggerFileDownload(
          response.data,
          response.headers["content-type"],
          this.filename
        );

        this.$message.success("导出成功");
      } catch (error) {
        console.error("Error downloading:", error);
        this.$message.error("导出失败，请重试！");
      } finally {
        this.downloadLoading = false;
      }
    },

    // 辅助函数：触发文件下载
    async triggerFileDownload(data, contentType, filename) {
      const blob = new Blob([data], {
        type: contentType || "application/octet-stream"
      });
      const downloadUrl = URL.createObjectURL(blob);

      const link = document.createElement("a");
      link.href = downloadUrl;
      link.download = filename;
      link.style.display = "none";

      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);

      URL.revokeObjectURL(downloadUrl);
    },
    fetchData() {
      this.listLoading = true;
      let params = Object.assign({}, this.searchValue);
      if (!params.level || params.level == "") {
        delete params.level;
      }
      if (!params.username || params.username == "") {
        delete params.username;
      }
      if (!params.work_name || params.work_name == "") {
        delete params.work_name;
      }
      getWorksList(params).then(res => {
        this.tableData = res.list;
        this.total = res.total;
        this.listLoading = false;
      });
    }
  }
};
</script>
<style scoped>
::v-deep .el-pagination.is-background .el-pager li:not(.disabled).active {
  background: #00bfd6 !important;
}
.titlebus {
  width: 300px;
  max-width: 300px;
  cursor: pointer;
}
</style>
